<template>
  <el-dialog :title="isEdit ? '编辑用户' : '新增用户'" v-model="visible" width="500px" @close="handleClose">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username" :disabled="isEdit" />
      </el-form-item>
      <el-form-item label="密码" prop="password" v-if="!isEdit">
        <el-input v-model="form.password" type="password" show-password />
      </el-form-item>
      <el-form-item label="真实姓名" prop="realName">
        <el-input v-model="form.realName" />
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="form.email" />
      </el-form-item>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="form.phone" />
      </el-form-item>
      <el-form-item label="部门" prop="departmentId" v-if="isEdit">
        <el-select v-model="form.departmentId" placeholder="请选择部门">
          <el-option
            v-for="dept in departments"
            :key="dept.id"
            :label="dept.name"
            :value="dept.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-switch v-model="form.status" active-value="1" inactive-value="0" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">确定</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch } from "vue";
import { ElMessage } from "element-plus";
import { createUser, updateUser } from "@/api/user";

const props = defineProps({
  modelValue: Boolean,
  userData: Object,
  departments: Array,
});

const emit = defineEmits(["update:modelValue", "success"]);

const formRef = ref();
const loading = ref(false);

const form = reactive({
  id: null,
  username: "",
  password: "",
  realName: "",
  email: "",
  phone: "",
  departmentId: null,
  status: "1",
});

const rules = {
  username: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 3, max: 20, message: "长度在 3 到 20 个字符", trigger: "blur" },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" },
  ],
  realName: [{ required: true, message: "请输入真实姓名", trigger: "blur" }],
  email: [{ type: "email", message: "请输入正确的邮箱地址", trigger: "blur" }],
  phone: [
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号",
      trigger: "blur",
    },
  ],
  departmentId: [{ required: true, message: "请选择部门", trigger: "change" }],
};

const visible = computed({
  get: () => props.modelValue,
  set: (val) => emit("update:modelValue", val),
});

const isEdit = computed(() => !!props.userData);

const resetForm = () => {
  Object.assign(form, {
    id: null,
    username: "",
    password: "",
    realName: "",
    email: "",
    phone: "",
    departmentId: null,
    status: "1",
  });
  formRef.value?.clearValidate();
};

const handleClose = () => {
  visible.value = false;
  resetForm();
};

const handleSubmit = async () => {
  if (!formRef.value) return;

  // 根据编辑/创建模式动态调整验证规则
  if (isEdit.value) {
    // 编辑模式下移除密码验证
    delete rules.password;
  } else {
    // 创建模式下添加密码验证
    rules.password = [
      { required: true, message: "请输入密码", trigger: "blur" },
      { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" },
    ];
  }

  await formRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true;
      try {
        // 构建提交数据，编辑时不包含密码
        const submitData = { ...form };
        if (isEdit.value) {
          delete submitData.password;
          await updateUser(form.id, submitData);
          ElMessage.success("更新成功");
        } else {
          await createUser(submitData);
          ElMessage.success("创建成功");
        }
        emit("success");
        handleClose();
      } catch (error) {
        ElMessage.error(error.message || "操作失败");
      } finally {
        loading.value = false;
      }
    }
  });
};

watch(
  () => props.userData,
  (newVal) => {
    if (newVal) {
      Object.assign(form, newVal);
    } else {
      resetForm();
    }
  },
  { immediate: true }
);
</script>